//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using ManagementStudioServices.Interfaces;
using Microsoft.Research.ScientificWorkflow.ManagementStudioControls.Common;
using Microsoft.Research.ScientificWorkflow.ManagementStudioModels;
using Microsoft.Research.ScientificWorkflow.TridentUtilities;
using Microsoft.Research.ScientificWorkflow.UIDesigner.WpfComposite;
using Microsoft.Practices.Unity;
using SR = Microsoft.Research.DataLayer;


namespace Microsoft.Research.ScientificWorkflow.ManagementStudioControls.WorkflowManagerModule
{
    /// <summary>
    /// A presentation model for the available workflows table in the center pane.
    /// </summary>
    public class AvailableWorkflowsListPresenter : IListPresenter, INotifyPropertyChanged
    {
        #region Private variables
        /// <summary>
        /// The unity container instance.
        /// </summary>
        private IUnityContainer container;

        /// <summary>
        /// The workflow manager service instance.
        /// </summary>
        private IWorkflowManagerService workflowManagerService;

        /// <summary>
        /// The search view for the available workflows filter.
        /// </summary>
        private UIElement searchView;

        /// <summary>
        /// The Title on the tableview.
        /// </summary>
        private string listViewTitle;

        /// <summary>
        /// The view which displays the workflows.
        /// </summary>
        private UIElement availableWorkflowsListView;

        /// <summary>
        /// The menu items for the listview items.
        /// </summary>
        private Collection<MenuItem> contextMenuItems;

        /// <summary>
        /// The selected item in the listview.
        /// </summary>
        private int selectedIndex;

        /// <summary>
        /// The items to be displayed on the tableview.
        /// </summary>
        private ObservableCollection<object> items;

        /// <summary>
        /// Flag to check if items were retreived in the query. 
        /// </summary>
        private bool emptyList;

        /// <summary>
        /// Flag to check if a job is selected.
        /// </summary>
        private bool workflowSelected = true;
        
        /// <summary>
        /// Holds the selectedWorkflow
        /// </summary>
        private WorkflowViewModel selectedWorkflow; 

        /// <summary>
        /// Holds the current filter.
        /// </summary>
        private string currentFilter;

        private string workflowName;
        private string createdBy;
        private string keyWord;

        #endregion

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="container">The unity contaier</param>
        /// <param name="view">The center pane view of the presenter.</param>
        /// <param name="service">The workflow manager service</param>
        public AvailableWorkflowsListPresenter(IUnityContainer container, AvailableWorkflowsListView view, IWorkflowManagerService service)
        {
            this.container = container;
            this.availableWorkflowsListView = view;
            this.workflowManagerService = service;

            this.items = new ObservableCollection<object>();
            this.ListViewTitle = ManagementStudioResourceManager.GetString("TableTitleAvailableWorkflows");
            this.searchView = this.container.Resolve<AvailableWorkflowsSearchView>();
            (this.searchView as AvailableWorkflowsSearchView).DataContext = this;
            (this.availableWorkflowsListView as AvailableWorkflowsListView).DataContext = this;
            this.Items.CollectionChanged += Items_CollectionChanged;

            // Initialize commands.
            this.JobDetailExpanded = new DelegateCommand<ListViewItem>(ExecuteJobDetailSelected);
            this.JobDetailCollapsed = new DelegateCommand<ListViewItem>(ExecuteJobDetailCollapsed);
            this.DeleteWorkflowCommand = new DelegateCommand<WorkflowViewModel>(ExecuteDeleteWorkflow, WorkflowCommandsCanDelete);
            this.EditWorkflowCommand = new DelegateCommand<WorkflowViewModel>(ExecuteEditWorkflow, WorkflowCommandsCanEdit);
            this.CreateJobCommand = new DelegateCommand<WorkflowViewModel>(ExecuteJobCreate, WorkflowCommandsCanExecute);
            this.ScheduleWorkflowCommand = new DelegateCommand<WorkflowViewModel>(ExecuteScheduleCreate, WorkflowCommandsCanExecute);
            this.WorkflowSelectedCommand = new DelegateCommand<bool>(p => { this.workflowSelected = p; this.RaiseCanExecuteEvents(); });
            this.WorkflowSelectChangedCommand = new DelegateCommand<WorkflowViewModel>(p => { this.selectedWorkflow = p; this.RaiseCanExecuteEvents(); });
            this.RefreshListCommand = new DelegateCommand<object>(p => { this.DisplayItems(this.currentFilter); });
            this.SearchCommand = new DelegateCommand<object>(p => this.SearchCommandExecute());

            // Set the context menu items for the items of the listview.
            this.SetContextMenuItems();
            this.DeleteWorkflowCommand.RaiseCanExecuteChanged();
            this.EditWorkflowCommand.RaiseCanExecuteChanged();

        }

        #region Public Properties
        /// <summary>
        /// The command executed when the search button is clicked.
        /// </summary>
        public DelegateCommand<object> SearchCommand { get; private set; }

        /// <summary>
        /// The command executed when the user clicks on the job details button of a workflow to expand.
        /// </summary>
        public ICommand JobDetailExpanded { get; private set; }

        /// <summary>
        /// The command executed when the user clicks on the job details button of a workflow to collapse.
        /// </summary>
        public ICommand JobDetailCollapsed { get; private set; }

        /// <summary>
        /// The command executed when the user clicks on the create job now command.
        /// </summary>
        public DelegateCommand<WorkflowViewModel> CreateJobCommand { get; private set; }

        /// <summary>
        /// The command executed when the user deletes a workflow.
        /// </summary>
        public DelegateCommand<WorkflowViewModel> DeleteWorkflowCommand { get; private set; }

        /// <summary>
        /// The command executed when the user wants to edit a workflow.
        /// </summary>
        public DelegateCommand<WorkflowViewModel> EditWorkflowCommand { get; private set; }

        /// <summary>
        /// The command executed when the user wants to schedule a workflow.
        /// </summary>
        public DelegateCommand<WorkflowViewModel> ScheduleWorkflowCommand { get; private set; }

        /// <summary>
        /// The command executed when the user selects a workflow.
        /// </summary>
        public DelegateCommand<bool> WorkflowSelectedCommand { get; private set; }

        /// <summary>
        /// The command executed when the user selects a workflow.
        /// </summary>
        public DelegateCommand<WorkflowViewModel> WorkflowSelectChangedCommand { get; private set; }

        /// <summary>
        /// The command to refresh the list.
        /// </summary>
        public DelegateCommand<object> RefreshListCommand { get; private set; }

        /// <summary>
        /// Property to check if items were retreived in the query.
        /// </summary>
        public bool EmptyList
        {
            get
            {
                return this.emptyList;
            }
            private set
            {
                this.emptyList = value;
                this.OnNotifyPropertyChanged("EmptyList");
            }
        }

        /// <summary>
        /// Search workflowname
        /// </summary>
        public string WorkflowName
        {
            get
            {
                return workflowName;
            }
            set
            {
                this.workflowName = value;
            }
        }
        /// <summary>
        /// Search createdby
        /// </summary>
        public string CreatedBy
        {
            get
            {
                return this.createdBy;
            }
            set
            {
                this.createdBy = value;
            }
        }
        /// <summary>
        /// search keyword
        /// </summary>
        public string Keyword
        {
            get
            {
                return this.keyWord;
            }
            set
            {
                this.keyWord = value;
            }
        }

        #endregion


        #region IListPresenter Members

        /// <summary>
        /// The items to be displayed in the table view.
        /// </summary>
        public ObservableCollection<object> Items
        {
            get
            {
                return this.items;
            }
        }

        /// <summary>
        /// The title of the table view.
        /// </summary>
        public string ListViewTitle
        {
            get
            {
                return this.listViewTitle;
            }
            set
            {
                this.listViewTitle = value;
                this.OnNotifyPropertyChanged("ListViewTitle");
            }
        }

        /// <summary>
        /// Display the items in the table view.
        /// </summary>
        /// <param name="queryString"></param>
        public void DisplayItems(string queryString)
        {
            try
            {
                Items.Clear();

                SR.Activity.ISearch.ISearchClause clause = null;
                if (!string.IsNullOrEmpty(queryString))
                {
                    this.currentFilter = queryString;
                    if (queryString.Equals(ManagementStudioControlsConstants.RECENTLYCREATEDWORKFLOWS, StringComparison.OrdinalIgnoreCase))
                    {
                        DateTime cutoffDate = DateTime.Today.AddDays(-5);
                        clause = SR.Activity.ISearch.CreatedDate(SR.DateTimeField.Condition.AfterOrEqual, cutoffDate);
                    }
                    else if (queryString.Equals(ManagementStudioControlsConstants.WORKFLOWSCREATEDBYMEFILTERNAME, StringComparison.OrdinalIgnoreCase))
                    {
                        clause = SR.Activity.ISearch.OwnerUserPrincipal(SR.ObjectFieldBase.Condition.Equals, TridentAuthentication.LoggedInUser);
                    }
                }

                // Get the required items.
                Collection<SR.Activity> workflowList = this.workflowManagerService.GetAvailableWorkflows(clause);

                // Set the selected Index. Show the empty message if no items found.
                if (workflowList != null && workflowList.Count > 0)
                {
                    this.EmptyList = false;
                    this.workflowSelected = true;

                    // Set status.
                    this.container.Resolve<IStatusMessageControl>().SetText(ManagementStudioResourceManager.GetString("StatusWorkflowCount",
                        workflowList.Count.ToString(CultureInfo.CurrentUICulture)));

                    // Add the items to the list.
                    foreach (SR.Activity workflow in workflowList)
                    {
                        WorkflowViewModel workflowViewmodel = new WorkflowViewModel(workflow);
                        Items.Add(workflowViewmodel);
                    }
                    this.SelectedIndex = 0;
                }
                else
                {
                    // Set the empty list property to true. Shows the empty list message and disables the buttons.
                    this.EmptyList = true;
                    this.container.Resolve<IStatusMessageControl>().SetText(string.Empty);
                }

                this.RaiseCanExecuteEvents();
            }
            catch (TridentCustomException ex)
            {
                TridentErrorHandler.HandleTridentCustomExceptionInUI(ex);
            }
        }

        /// <summary>
        /// The search view for the available workflows filter.
        /// </summary>
        public UIElement SearchView
        {
            get
            {
                return this.searchView;
            }
        }

        /// <summary>
        /// The view which displays the workflows.
        /// </summary>
        public UIElement ListView
        {
            get
            {
                return this.availableWorkflowsListView;
            }
        }

        /// <summary>
        /// The menu items for the listview items.
        /// </summary>
        public Collection<MenuItem> MenuItemCollection
        {
            get
            {
                return this.contextMenuItems;
            }
        }

        /// <summary>
        /// The selected index of the list.
        /// </summary>
        public int SelectedIndex
        {
            get
            {
                return this.selectedIndex;
            }
            set
            {
                this.selectedIndex = value;
                this.OnNotifyPropertyChanged("SelectedIndex");
            }
        }

        #endregion

        #region INotifyPropertyChanged Members

        /// <summary>
        /// The property changed event. Fired when a proprty value changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Fires the property changed event.
        /// </summary>
        /// <param name="propertyName">Name of the property which has been modified.</param>
        private void OnNotifyPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// The command executed when the user clicks on the show job details button of a workflow.
        /// </summary>
        /// <param name="selectedListViewItem">The listview selected.</param>
        private void ExecuteJobDetailSelected(ListViewItem selectedListViewItem)
        {
            try
            {
                // Retrieve the workflow view model which is the datacontext of the listviewitem.
                WorkflowViewModel selectedWorkflow = selectedListViewItem.DataContext as WorkflowViewModel;

                // Create a Joblist presenter and retrieve the jobs for th workflow.
                WorkflowJobListPresenter jobListPresenter = this.container.Resolve<WorkflowJobListPresenter>();
                jobListPresenter.DisplayItems(selectedWorkflow as WorkflowViewModel);

                // Find the border in the controltemplate of the listview and insert the joblist view into the border.
                ControlTemplate template = selectedListViewItem.Template;
                Border borderToInsert = template.FindName("jobsListHost", selectedListViewItem) as Border;
                borderToInsert.Child = jobListPresenter.View;
                borderToInsert.Visibility = Visibility.Visible;
            }
            catch (TridentCustomException ex)
            {
                TridentErrorHandler.HandleTridentCustomExceptionInUI(ex);
            }
        }

        /// <summary>
        /// The command executed when the user clicks on the hide job details button of a workflow.
        /// </summary>
        /// <param name="selectedListViewItem">The listview selected.</param>
        private void ExecuteJobDetailCollapsed(ListViewItem selectedListViewItem)
        {
            // Find the border in the controltemplate of the listview and insert the joblist view into the border.
            ControlTemplate template = selectedListViewItem.Template;
            Border borderToInsert = template.FindName("jobsListHost", selectedListViewItem) as Border;

            borderToInsert.Child = null;
            borderToInsert.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// Delete the seleted workflow.
        /// </summary>
        /// <param name="selectedWorkflow">The workflow to be deleted.</param>
        private void ExecuteDeleteWorkflow(WorkflowViewModel selectedWorkflow)
        {
            try
            {
                if (selectedWorkflow != null)
                {
                    // Check if the workflow has been deleted.
                    if (this.workflowManagerService.IsWorkflowDeleted(selectedWorkflow.WorkflowId))
                    {
                        TridentMessageBox.ShowTridentErrorMessageBox(ManagementStudioResourceManager.GetString("WorkflowAlreadyDeleted"));
                        return;
                    }

                    // Get a confirmation from the user.
                    MessageBoxResult result = TridentMessageBox.ShowTridentConfirmationYesNoMessageBox(
                        ManagementStudioResourceManager.GetString("DeleteWorkflowConfirmation"));

                    if (result == MessageBoxResult.Yes)
                    {
                        this.workflowManagerService.DeleteWorkflow(selectedWorkflow.WorkflowId);

                        // Delete the item from the current items list. It reflects in the listview.
                        this.Items.Remove(selectedWorkflow);
                    }
                }
            }
            catch (TridentCustomException ex)
            {
                TridentErrorHandler.HandleTridentCustomExceptionInUI(ex);
            }
        }

        /// <summary>
        /// Open the workflow in trident composer for edit.
        /// </summary>
        /// <param name="selectedWorkflow">The Workflow to be edited.</param>
        private void ExecuteEditWorkflow(WorkflowViewModel selectedWorkflow)
        {
            try
            {
                if (selectedWorkflow != null)
                {
                    // Check if the workflow has been deleted.
                    if (this.workflowManagerService.IsWorkflowDeleted(selectedWorkflow.WorkflowId))
                    {
                        TridentMessageBox.ShowTridentErrorMessageBox(ManagementStudioResourceManager.GetString("WorkflowAlreadyDeleted"));
                        return;
                    }

                    this.workflowManagerService.OpenComposerForEdit(selectedWorkflow.WorkflowId);
                }
            }
            catch (TridentCustomException ex)
            {
                TridentErrorHandler.HandleTridentCustomExceptionInUI(ex);
            }
            catch (Exception ex)
            {
                TridentErrorHandler.HandleKnownExceptionsInUI(ex);
            }
        }

        /// <summary>
        /// Open the execute now window for the user to enter execute details.
        /// </summary>
        /// <param name="selectedWorkflow">The workflow selected.</param>
        private void ExecuteJobCreate(WorkflowViewModel selectedWorkflow)
        {
            try
            {
                if (selectedWorkflow != null)
                {
                    // Check if the workflow has been deleted.
                    if (this.workflowManagerService.IsWorkflowDeleted(selectedWorkflow.WorkflowId))
                    {
                        TridentMessageBox.ShowTridentErrorMessageBox(ManagementStudioResourceManager.GetString("WorkflowAlreadyDeleted"));
                        return;
                    }

                    // Open the execute now window.
                    ExecuteWorkflowViewPresenter executePresenter = new ExecuteWorkflowViewPresenter(selectedWorkflow.WorkflowId,
                        this.container, new ExecuteWorkflowView(), this.workflowManagerService);

                    executePresenter.DisplayExecuteWorkflowWindow();
                }
            }
            catch (TridentCustomException ex)
            {
                TridentErrorHandler.HandleTridentCustomExceptionInUI(ex);
            }
            catch (Exception ex)
            {
                TridentErrorHandler.HandleKnownExceptionsInUI(ex);
            }
        }

        /// <summary>
        /// Opens the create schedule window to create a schedule in registry.
        /// </summary>
        /// <param name="selectedWorkflow">The workflow selected.</param>
        private void ExecuteScheduleCreate(WorkflowViewModel selectedWorkflow)
        {
            try
            {
                // Check if the workflow has been deleted.
                if (this.workflowManagerService.IsWorkflowDeleted(selectedWorkflow.WorkflowId))
                {
                    TridentMessageBox.ShowTridentErrorMessageBox(ManagementStudioResourceManager.GetString("WorkflowAlreadyDeleted"));
                    return;
                }

                if (selectedWorkflow != null)
                {
                    // Open the scheduler window.
                    SchedulerViewPresenter schedulerView =
                        new SchedulerViewPresenter(this.container, selectedWorkflow.WorkflowId, ScheduleMode.New, new SchedulerView(), this.workflowManagerService);
                }
            }
            catch (TridentCustomException ex)
            {
                TridentErrorHandler.HandleTridentCustomExceptionInUI(ex);
            }
            catch (Exception ex)
            {
                TridentErrorHandler.HandleKnownExceptionsInUI(ex);
            }
        }

        /// <summary>
        /// Checks if the workflow can be Deleted. It enables and disables the buttons and menuitems.
        /// </summary>
        /// <param name="selectedJob">The selected.Workflow</param>
        /// <returns>True if the workflow can be deleted. False otherwise.</returns>
        private bool WorkflowCommandsCanDelete(WorkflowViewModel selectedModel)
        {
            if (this.EmptyList || !this.workflowSelected)
            {
                return false;
            }

            if (this.items.Count > 0)
            {
                if (selectedModel != null)
                    return selectedModel.CanDelete;

                if (this.selectedWorkflow != null)
                    return this.selectedWorkflow.CanDelete;
            }

            return false;
        }


        /// <summary>
        /// Checks if the workflow can be Edited. It enables and disables the buttons and menuitems.
        /// </summary>
        /// <param name="selectedJob">The selected.Workflow</param>
        /// <returns>True if the workflow can be edited. False otherwise.</returns>
        private bool WorkflowCommandsCanEdit(WorkflowViewModel selectedModel)
        {
            if (this.EmptyList || !this.workflowSelected)
            {
                return false;
            }

            if (this.items.Count > 0)
            {
                if (selectedModel != null)
                    return selectedModel.CanEdit;

                if (this.selectedWorkflow != null)
                    return this.selectedWorkflow.CanEdit;
            }

            return false;
        }

        /// <summary>
        /// Checks if the workflow can be terminated. It enables and disables the buttons and menuitems.
        /// </summary>
        /// <param name="selectedJob">The job selected.</param>
        /// <returns>True if the workflow can be terminated. False otherwise.</returns>
        private bool WorkflowCommandsCanExecute(WorkflowViewModel selectedJob)
        {
            if (this.EmptyList || !this.workflowSelected)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// The menu items for the listview items.
        /// </summary>
        private void SetContextMenuItems()
        {
            this.contextMenuItems = new Collection<MenuItem>();

            MenuItem executeMenuitem = new MenuItem();
            executeMenuitem.Header = ManagementStudioResourceManager.GetString("MenuItemHeaderExecute");
            executeMenuitem.Icon = IconUtilities.GetIcon(@"pack://Application:,,,/Microsoft.Research.ScientificWorkflow.TridentUtilities;component/Images/ManagementStudio/execute.png");
            executeMenuitem.Command = this.CreateJobCommand;
            this.contextMenuItems.Add(executeMenuitem);

            MenuItem scheduleMenuitem = new MenuItem();
            scheduleMenuitem.Header = ManagementStudioResourceManager.GetString("MenuItemHeaderSchedule");
            scheduleMenuitem.Icon = IconUtilities.GetIcon(@"pack://Application:,,,/Microsoft.Research.ScientificWorkflow.TridentUtilities;component/Images/ManagementStudio/schedule.png");
            scheduleMenuitem.Command = this.ScheduleWorkflowCommand;
            this.contextMenuItems.Add(scheduleMenuitem);

            MenuItem editMenuitem = new MenuItem();
            editMenuitem.Header = ManagementStudioResourceManager.GetString("MenuItemHeaderEdit");
            editMenuitem.Icon = IconUtilities.GetIcon(@"pack://Application:,,,/Microsoft.Research.ScientificWorkflow.TridentUtilities;component/Images/ManagementStudio/edit.png");
            editMenuitem.Command = this.EditWorkflowCommand;
            this.contextMenuItems.Add(editMenuitem);

            MenuItem deleteMenuitem = new MenuItem();
            deleteMenuitem.Header = ManagementStudioResourceManager.GetString("MenuItemHeaderDelete");
            deleteMenuitem.Icon = IconUtilities.GetIcon(@"pack://Application:,,,/Microsoft.Research.ScientificWorkflow.TridentUtilities;component/Images/ManagementStudio/delete.png");
            deleteMenuitem.Command = this.DeleteWorkflowCommand;
            this.contextMenuItems.Add(deleteMenuitem);
        }

        /// <summary>
        /// Raise the can execute changed events so that the UI elements can be enabled/disabled.
        /// </summary>
        private void RaiseCanExecuteEvents()
        {
            this.CreateJobCommand.RaiseCanExecuteChanged();
            this.EditWorkflowCommand.RaiseCanExecuteChanged();
            this.DeleteWorkflowCommand.RaiseCanExecuteChanged();
            this.ScheduleWorkflowCommand.RaiseCanExecuteChanged();
        }

        /// <summary>
        /// Event handler for the collection changed event on the Items collection.
        /// </summary>
        /// <param name="sender">The source.</param>
        /// <param name="e">Event arguments</param>
        void Items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            ICollection<object> collection = sender as ICollection<object>;


            // If collection is empty then disable the buttons.
            this.EmptyList = (collection.Count == 0);
            this.RaiseCanExecuteEvents();
        }

        /// <summary>
        /// Dummy implementation for the search click button.
        /// </summary>
        private void SearchCommandExecute()
        {
            try
            {
                Items.Clear();

                // This is the place where the workflows are retrieved from the registry. The search call ideally goes here.
                // Get the required items.
                SR.Activity.ISearch.ISearchClause filter = null;
                List<SR.Activity.ISearch.ISearchClause> filterArray = new List<SR.Activity.ISearch.ISearchClause>();
                if (!string.IsNullOrEmpty(this.WorkflowName))
                {
                    filterArray.Add(SR.Activity.ISearch.Name(SR.StringField.Condition.Contains, this.WorkflowName));
                }
                if (!string.IsNullOrEmpty(this.Keyword))
                {
                    filterArray.Add(SR.Activity.ISearch.Keywords(SR.StringField.Condition.Contains, this.Keyword));
                }

                if (!string.IsNullOrEmpty(this.CreatedBy))
                {
                    filterArray.Add(SR.Activity.ISearch.CreatedBy(SR.StringField.Condition.Contains, this.CreatedBy));
                }
                if (filterArray.Count > 1)
                {
                    filter = SR.Activity.ISearch.AND(filterArray.ToArray());
                }
                else
                {
                    filter = filterArray.Count > 0 ? filterArray[0] : null;
                }

                Collection<SR.Activity> workflowList = workflowManagerService.GetAvailableWorkflows(filter);

                // Set the selected Index. Show the empty message if no items found.
                if (workflowList != null && workflowList.Count > 0)
                {
                    this.SelectedIndex = 0;
                    this.EmptyList = false;
                    this.workflowSelected = true;

                    // Set status.
                    this.container.Resolve<IStatusMessageControl>().SetText(ManagementStudioResourceManager.GetString("StatusWorkflowCount",
                        workflowList.Count.ToString(CultureInfo.CurrentUICulture)));

                    // Add the items to the list.
                    // As the Items property is a observable collection and is bound to the listview. Any changes here will be shown in the listview. 
                    foreach (SR.Activity workflow in workflowList)
                    {
                        WorkflowViewModel workflowViewmodel = new WorkflowViewModel(workflow);
                        Items.Add(workflowViewmodel);
                    }
                }
                else
                {
                    // Set the empty list property to true. Shows the empty list message and disables the buttons.
                    this.EmptyList = true;
                    this.container.Resolve<IStatusMessageControl>().SetText(string.Empty);
                }

                this.RaiseCanExecuteEvents();
            }
            catch (SR.RecordNotFoundException)
            {
                // Set status.
                this.container.Resolve<IStatusMessageControl>().SetText(ManagementStudioResourceManager.GetString("StatusWorkflowCount",
                    0.ToString(CultureInfo.CurrentUICulture)));
            }
            catch (TridentCustomException ex)
            {
                TridentErrorHandler.HandleTridentCustomExceptionInUI(ex);
            }
        }
        #endregion
    }
}
